<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\model\admin\TrainTypeModel;
use think\facade\Db;
use think\Request;

class TrainType extends AuthController
{
    public function list(Request $request)
    {
        // 所有的公司
        $companies = \app\model\company\Company::where('status', 1)
            ->select()
            ->toArray();
        array_unshift($companies, [
            'id' => 0,
            'company_name' => '平台',
        ]);
        return app('json')->success([
            'list' => DataType::getTrainType(),
            'companies' => $companies,
        ]);
    }

    private function getChildren($pid = 0)
    {
        return TrainTypeModel::where('status', 1)
            ->where('pid', $pid)
            ->select()
            ->each(function ($item) {
                $item['children'] = $this->getChildren($item['id']);
                $item['value'] = $item['id'];
                $item['label'] = $item['title'];
                return $item;
            })
            ->toArray();
    }

    public function info(Request $request)
    {

    }

    public function save(Request $request)
    {
        $param = $request->only([
            'title', 'pid'
        ]);
        $param['status'] = 1;
        if ($param['pid'] == 0) {
            $param['level'] = 1;
        } else {
            $param['level'] = TrainTypeModel::where('id', $param['pid'])
                    ->value('level') + 1;
        }
        TrainTypeModel::create($param);
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        $data = TrainTypeModel::where('id', $id)
            ->where('status', 1)
            ->find();
        if (!$data) {
            return app('json')->fail('数据不存在');
        } else {
            $exits = TrainTypeModel::where('pid', $id)
                ->where('status', 1)
                ->find();
            if ($exits) {
                return app('json')->fail('当前选择项有子分类，不可删除');
            }

            TrainTypeModel::update([
                'status' => -1,
            ], [
                'id' => $id,
            ]);
        }
        return app('json')->success();
    }
}